<?php
namespace XCall\Controller;
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of XToolController
 *
 * @author Alen
 */
class CtiManagerController extends \Think\Controller {

    protected $loginInfo;
    protected $isSeat = false;

    function __construct() {
        parent::__construct();
        $delogin = I('delogin');
        if (!$delogin) {
            $uid = I('uid');
            $extension = I('extension');
            if (!$uid && !$extension) {
                die($this->msg_format('未登录!'));
            }
            $loginInfo = $uid ? M('tuser_member')->find($uid) : M('tuser_member')->where("extensionNumber='$extension' and userType='SEAT'")->find();
            if (!$loginInfo) {
                die($this->msg_format('用户不存在!'));
            }
            $this->loginInfo = $loginInfo;
            $this->isSeat = $loginInfo['userType'] == 'SEAT';
        }
    }

    // 分机状态 2014-12-10 by sutroon
    public function seat_state() {
        $str = $this->seat_get_state();
        echo $this->msg_format($str);
        if(IS_AJAX){}
    }

    /**
     * 获取座席分机状态
     * @return string
     * @since 1.0 2014-12-10
     */
    function seat_get_state($extension = '') {
        if (!$this->isSeat) {
            return '非座席';
        }

        $cmd = 'queue show';
        $cacheId = str_replace(' ', '_', $cmd);
        $str = trim(asmanager_query_result($cmd));
        S($cacheId, $str, array('expire' => 10));

        $queue = '';
        if (!$extension) {
            $extension = $this->loginInfo['extensionNumber'];
        }
        $teamNumber = $this->loginInfo['teamNumber'];
        $sign = '签出';
        $paused = '';
        $status = '';
        $arr = preg_split("/[\n]+/", trim($str));
        foreach ($arr as $line) {
            if (!$line) {
                continue;
            }
            if (false !== strpos($line, ' strategy ')) {
                $pos = strpos($line, ' has ');
                $queue = substr($line, 0, $pos);
                if ($queue != $teamNumber) {
                    $queue = '';
                }
                continue;
            }
            if ($queue && false !== ($pos = strpos($line, "(SIP/$extension)"))) {
                $sign = '签入';
                if (false === strpos($line, '(paused)')) {
                    $paused = '示闲';
                } else {
                    $paused = '示忙';
                }
                if (false !== strpos($line, '(Not in use)')) {
                    $status = '空闲';
                }
                break;
            }
        }
        if ($sign == '签入') {
            $queue = "[$queue]";
        } else {
            $queue = '';
        }
        return trim("$queue $sign $paused");
    }

    // 座席挂机 2014-12-10 by sutroon
    public function seat_handup() {
        if (!$this->isSeat) {
            $this->act_ajaxReturn(false, '不是有效座席!');
        }
        $channel = $this->seat_get_call_channel();
        if (!$channel) {
            $this->act_ajaxReturn(false, '未通话!');
        }
        $astsm = create_asmanager();
        $result = $astsm->Hangup($channel);
        $this->act_ajaxReturn($result['Response'] == 'Success', $result['Response'] == 'Success' ? '操作成功!' : '操作失败：' . $result['Message']);
    }

    public function channel_handup() {
        $channel = I('channel');
        if (!$channel) {
            die('通道号无效');
        }
        $channel = str_replace('{xg}', '/', $channel);
        $astsm = create_asmanager();
        $result = $astsm->Hangup($channel);
        $this->act_ajaxReturn($result['Response'] == 'Success', $result['Response'] == 'Success' ? '操作成功!' : '操作失败：' . $result['Message']);
    }

    /**
     * 获取座席当前通话的通道值
     * @param bool $pair 是否查找对应通道
     * @param string $extension 分机号
     * @return bool|string|array
     * @since 1.0 2014-12-10 by sutroon
     */
    function seat_get_call_channel($pair = false, $extension = '') {
        // core show channels concise
        $cmd = 'core show channels verbose';
        $cacheId = str_replace(' ', '_', $cmd);
        $str = trim(asmanager_query_result($cmd));
        if (I('debug') == '1') {
            echo "<pre>$str</pre>";
        }
        S($cacheId, $str, array('expire' => 10));
        $arr = preg_split("/[\n]+/", trim($str));
        $channel = '';
        if (!$extension) {
            $extension = $this->loginInfo['extensionNumber'];
        }
        foreach ($arr as $line) {
            $pos = strpos($line, "SIP/$extension-");
            if (false === $pos || $pos > 0) {
                continue;
            }
            $channel = substr($line, 0, strpos($line, ' '));
            break;
        }
        $channel2 = '';
        if ($pair) {
            foreach ($arr as $line) {
                $pos = strpos($line, $channel);
                if (false === $pos || $pos == 0) {
                    continue;
                }
                $channel2 = substr($line, 0, strpos($line, ' '));
                break;
            }
        }
        if (!$channel) {
            return false;
        }
        return $pair ? array($channel, $channel2) : $channel;
    }

    // 座席保持恢复 2014-12-10 by sutroon
    public function seat_callpark() {
        $astsm = create_asmanager();
        $channels = $this->seat_get_call_channel(true);
        if (!$channels || !$channels[1]) {
            $this->act_ajaxReturn(false, '未通话!');
        }
        $opt = strtolower(I('opt'));
        if (!in_array($opt, array('y', 'n'))) {
            $this->act_ajaxReturn(false, '无效操作!');
        }

        /*
          if ($opt == 'n') {
          $cmd='Stopped music on hold on '.$channels[1];
          $result = $astman->Command($cmd);
          echo $cmd.'<br />执行结果：';
          var_export($result);
          $isSuccess = strpos($result['data'], 'paused interface') !== false;
          } else {
          $cmd='channel redirect '.$channels[0];
          $cmd="Started music on hold, class 'default', on ".$channels[0];
          $result = $astman->Command($cmd);
          echo $cmd.'<br />执行结果：';
          var_export($result);
          $isSuccess = strpos($result['data'], 'unpaused interface') !== false;
          }
          //$this->act_ajaxReturn($isSuccess, $isSuccess ? '操作成功!' : '操作失败：' . $result['Response']);
         */
        $chn0 = str_replace(':', '/', I('chn0'));
        $chn1 = str_replace(':', '/', I('chn1'));
        //$params = array('ControllerID' => '1', 'Channel' => ($chn0 ? $chn0 : $channels[0]), 'Channel2' => ($chn1 ? $chn1 : $channels[1]), 'Timeout' => null, 'Parkinglot' => null);
        //$result = $astsm->send_request('Park', $params);

        $params = array('Channel' => $channels[0], 'Event' => 'hold');
        $result = $astsm->send_request('SIPnotifychan', $params);
        //echo "params:<br />";
        //var_export($params);
        //echo '<br />result:<br />';
        //var_export($result);

        $this->act_ajaxReturn($result['Response'] == 'Success', $result['Response'] == 'Success' ? '操作成功!' : '操作失败：' . $result['Message']);
    }

    // 座席试听录音 2015-2-13 by sutroon
    public function seat_listen() {
        if (!$this->isSeat) {
            $this->act_ajaxReturn(false, '不是有效座席!');
        }
        $extension = $this->loginInfo['extensionNumber'];
        $file = I('file');
        $result = $this->login_extension_static($queue, $extension, $opt);
        $this->act_ajaxReturn($result['result'], $result['result'] ? '操作成功!' : '操作失败：' . $result['Message']);
    }

    // 座席签入签出 2014-12-9 by sutroon
    public function seat_sign() {
        if (!$this->isSeat) {
            $this->act_ajaxReturn(false, '不是有效座席!');
        }
        $opt = strtolower(I('opt'));
        if (!in_array($opt, array('login', 'loginout'))) {
            $this->act_ajaxReturn(false, '无效操作!');
        }
        $extension = $this->loginInfo['extensionNumber'];
        $queue = $this->loginInfo['teamNumber'];
        $result = $this->login_extension_static($queue, $extension, $opt);
        $this->act_ajaxReturn($result['result'], $result['result'] ? '操作成功!' : '操作失败：' . $result['Message']);
    }

    // 座席示闲示忙 2014-12-9 by sutroon
    public function seat_queuePause() {
        if (!$this->isSeat) {
            $this->act_ajaxReturn(false, '不是有效座席!');
        }
        $opt = strtolower(I('opt'));
        if (!in_array($opt, array('busy', 'free'))) {
            $this->act_ajaxReturn(false, '无效操作!');
        }
        $extension = $this->loginInfo['extensionNumber'];
        $queue = I('queue', $this->loginInfo['teamNumber']);
        $astman = create_asmanager();
        if ($opt == 'busy') {
            $result = $astman->Command("queue pause member SIP/$extension queue $queue reason DoingCallbacks");
            $isSuccess = strpos($result['data'], 'paused interface') !== false;
        } else {
            $result = $astman->Command("queue unpause member SIP/$extension queue $queue reason off-break");
            $isSuccess = strpos($result['data'], 'unpaused interface') !== false;
        }
        // $result = $astsm->send_request('QueuePause', array('ControllerID' => null, 'Interface' => "sip/$extension", 'Paused' => ($opt == 'busy'), 'Queue' => $queue,'Reason'=>null));
        $this->act_ajaxReturn($isSuccess, $isSuccess ? '操作成功!' : '操作失败：' . $result['Response']);
    }

    // 呼叫号码 2014-12-5 by sutroon
    public function seat_dialout_save() {
        $phone = I('phone');
        if (!$phone) {
            $this->act_ajaxReturn(false, '呼叫号码无效');
        }
        if ($this->loginInfo['userType'] != 'SEAT') {
            $this->act_ajaxReturn(false, '不是有效座席');
        }
        $list = M()->query('select u.extensionNumber, u.teamNumber, u.ctiTrunk, u.ctiCallerNo, u.ctiRegMode, tk.context from tuser_member u left join tcti_trunk tk on u.ctiTrunk=tk.account where u.id=' . $this->loginInfo['id']);
        if (!$list) {
            $this->act_ajaxReturn(false, '座席数据无效!');
        }
        $context = $list[0]['context'];
        // $context = 'xcall';
        $result = $this->dialout_func($list[0]['extensionNumber'], $phone, $list[0]['ctiTrunk'], $context, $list[0]['ctiCallerNo']);
        $this->act_ajaxReturn(true === $result, true === $result ? '正在发起呼叫...' : $result);
    }

    /**
     * 判断座席分机是否空闲
     * @return boolean
     * @since 1.0 2014-12-10
     */
    function seat_check_idle($extension) {
        $cmd = 'core show hints';
        $cacheId = str_replace(' ', '_', $cmd);
        $str = trim(asmanager_query_result($cmd));
        if (I('debug') == '1') {
            echo "<pre>$str</pre>";
        }
        S($cacheId, $str, array('expire' => 10));
        $arr = preg_split("/[\n]+/", trim($str));
        foreach ($arr as $line) {
            $sip_name = explode("@", $line);
            $name = trim($sip_name[0]);
            if ($name[0] == '*') {
                continue;
            }
            if ($name != $extension) {
                continue;
            }
            if (false !== strpos($line, 'State:Idle')) {
                return true;
            }
        }
        return false;
    }

    // 座席转接 2014-12-10
    public function seat_trans_edit() {
        if (!$this->isSeat) {
            $this->act_close_dialog(false, '不是有效座席', '', false);
        }
        $this->display();
    }

    // 座席转接 2014-12-10 by sutroon
    public function seat_trans_edit_save() {
        $exten = I('exten');
        if (!$exten) {
            $this->act_error('转接号码未填写!');
        }
        $str = $this->seat_get_state($exten);
        if (!$this->seat_check_idle($exten)) {
            $this->act_error("$exten 不是空闲状态!");
        }
        $channels = $this->seat_get_call_channel(true);
        $channel = $channels[1];
        $extrachannel = $channels[0];
        if (!$channel) {
            $this->act_error("转接失败!");
        }
        $context = 'xcall';
        $priority = 1;
        $astsm = create_asmanager();
        $result = $astsm->Redirect($channel, $extrachannel, $exten, $context, $priority);
        $this->act_close_dialog($result['Response'] == 'Success', '转接%' . ($result['Response'] == 'Success' ? '' : $result['Message']) . '!', '', false);
    }

    // (2015-1-1已废弃,迁移到XCallApi/CallRecordController) 座席来电弹屏 2014-12-16 by sutroon
    public function seat_screen_popup() {
        $extension = $this->loginInfo['extensionNumber'];
        if (!$extension) {
            die('');
        }
        $M = M('tcti_call_record');
        $data = $M->field('id, extension, lineNum')->where("extension='$extension' and state=0")->order('id desc')->find();
        $M->where("extension='$extension' and state=0")->setField('state', 1);
        echo 'extension_screen_popup_jsonp(' . json_encode($data) . ')';
    }

    // (2015-1-1已废弃,迁移到XCallApi/CallRecordController)座席获取最近10条通话记录 2014-12-16 by sutroon
    public function seat_get_call_record_list() {
        $extension = $this->loginInfo['extensionNumber'];
        if (!$extension) {
            die('');
        }
        $cdrlist = M('tcti_call_record')->field('lineNum,createdTime')->where("extension='$extension'")->order('id desc')->limit(10)->select();
        echo 'extension_call_record_list_jsonp(' . json_encode($cdrlist) . ')';
    }

    // 登入静态分机
    function login_extension_static($queue, $extension, $opt = 'login') {
        $astman = create_asmanager();
        $queue = $queue;
        $interface = 'SIP/' . $extension;
        if ($opt == 'login') {
            //$result = $astman->QueueAdd($queue, $interface);  // 不能用这种方式签入,这种方式登入结果是SIP/301,正确的是301 (SIP/301)
            $result = $astman->Command('queue add member SIP/' . $extension . ' to ' . $queue . ' penalty 0 as ' . $extension . ' state_interface SIP/' . $extension);
            $isSuccess = strpos($result['data'], 'Added interface') !== false;
        } else {
            //$result = $astman->QueueRemove($queue, $interface); // 移除队列
            //$isSuccess = $result['Response'] == 'Success';
            $result = $astman->Command("queue remove member SIP/$extension from $queue");
            $isSuccess = strpos($result['data'], 'Removed') !== false;
        }
        return array('result' => $isSuccess, 'Message' => $result['Message']);
    }

    /**
     * 发起呼叫
     * <br />成功则返回true,否则返回错误消息
     * <br />[注意]有时候落地改来改去可能会导致呼叫失败,所以如果遇到呼叫失败,先查一下落地是否正确,改用呼vos分机号测试
     * @param $phoneNumber
     * @param $trunkName
     * @param $context
     * @param $callerNo
     * @return bool
     * @since 1.0 2014-12-5 by sutroon 重构
     */
    function dialout_func($extension, $phoneNumber, $trunkName, $context, $callerNo) {
        //set_time_limit(0);
        //ob_implicit_flush(false);

        /*
          $params = array(
          'Channel' => "SIP/$extension", // 如果是电话则 Local/015003069007@user
          'Application' => 'Dial',
          'Data' => "SIP/$trunkName/$phoneNumber",
          'Priority' => 1,
          'Timeout' => 45000, // 等待被叫应答振铃时间
          // 'CallerID'=>$callerNo, // 来电显示的号码
          // 'Exten'=>'', 调用的拨号方案，对方接听电话后我们在这里实现交互
          );
          $result = $astman->send_request('Originate', $params);
          return $result['Response'] == 'Success' ? true : $result['Message'];
         */
        $params['Channel'] = "SIP/$extension";
        $params['Application'] = 'Dial';
        $params['Data'] = 'Local/' . $phoneNumber . '@xcall/n';
        $params['Priority'] = 1;
        $params['Timeout'] = 45000;
        $astman = create_asmanager();
        $result = $astman->send_request("Originate", $params);
        return $result['Response'] == 'Success' ? true : $result['Message'];
    }

    function dialout_func2($extension, $phoneNumber, $trunkName, $context, $callerNo) {
        $strategyID = 0;
        $taskID = 0;
        $siteID = 0;
        $sayExtension = 0;
        $outEcEnable = 0;
        $uniqid = $extension.'.'.$phoneNumber.'.'.date('Ymdhis');
        $params['Account'] = $strategyID . "." . $taskID . "." . $siteID . "." . $sayExtension . "." . $outEcEnable . "." . $soureceID . ".OUT." . $uniqid;
        $params['Channel'] = "SIP/$extension";
        $params['Application'] = 'Dial';
        $params['Data'] = 'Local/' . $phoneNumber . '@xcall/n';
        $params['Priority'] = 1;
        $params['Timeout'] = 45000;
        $astman = create_asmanager();
        $result = $astman->send_request("Originate", $params);
    }

    /**
     * 返回ajax数据
     * @param bool $result 结果标识
     * @param string|array $message 消息
     * @since 1.0 2014-11-27 by sutroon; 1.1 2014-12-16 by sutroon 新增jsonp支持
     */
    function act_ajaxReturn($result, $message) {
        if (is_array($message)) {
            $msg = implode("<br />", $message);
        } else {
            if (false !== strpos($message, '%')) {
                $msg = str_replace('%', false === $result ? '失败' : '成功', $message);
            } else {
                $msg = $message;
            }
        }
        $data = array("success" => (false === $result ? 0 : 1), "message" => $msg);
        $jsonp = I('jsonp');
        if ($jsonp) {
            echo $jsonp . '(' . json_encode($data) . ')';
        } else {
            $this->ajaxReturn($data);
        }
        exit;
    }

    /**
     * 消息格式化
     * @param type $msg
     * @return type
     * @since 1.0 2014-12-16 by sutroon
     */
    function msg_format($msg) {
        $jsonp = I('jsonp');
        if ($jsonp) {
            return $jsonp . '(' . json_encode($msg) . ')';
        }
        return $msg;
    }

}
